﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Resources;
using System.IO;

namespace ResourceExtension
{
    public class ResourceXManager : ResourceManager
    {
        Dictionary<string, ResourceMap> queriesMap =
            new Dictionary<string, ResourceMap>();

        public string PrimaryQuery { get; set; }

        public ResourceXManager(Type resourceType)
            : base(resourceType)
        {
            PrimaryQuery = string.Empty;
        }

        public ResourceXManager(string s, Assembly assembly)
            : this(assembly.GetType(s))
        { }

        public void Add(string query, Stream resourceStream)
        {
            queriesMap.Add(query, ResourceXReader.Read(resourceStream));
        }

        public bool Exist(string query)
        {
            return queriesMap.ContainsKey(query);
        }

        public override string GetString(string name)
        {
            ResourceMap resourceMap;
            if (queriesMap.TryGetValue(PrimaryQuery, out resourceMap))
            {
                object value;
                if (resourceMap.TryGetValue(name, out value))
                {
                    return value as string;
                }
            }
            return base.GetString(name);
        }

        public override string GetString(string name, System.Globalization.CultureInfo culture)
        {
            ResourceMap resourceMap;
            if (queriesMap.TryGetValue(PrimaryQuery, out resourceMap))
            {
                object value;
                if (resourceMap.TryGetValue(name,out value))
                {
                    return value as string;
                }
            }
            return base.GetString(name, culture);
        }

        public override object GetObject(string name)
        {
            ResourceMap resourceMap;
            if (queriesMap.TryGetValue(PrimaryQuery, out resourceMap))
            {
                object value;
                if (resourceMap.TryGetValue(name, out value))
                {
                    return value;
                }
            }
            return base.GetObject(name);
        }

        public override object GetObject(string name, System.Globalization.CultureInfo culture)
        {
            ResourceMap resourceMap;
            if (queriesMap.TryGetValue(PrimaryQuery, out resourceMap))
            {
                object value;
                if (resourceMap.TryGetValue(name, out value))
                {
                    return value;
                }
            }
            return base.GetObject(name, culture);
        }
    }
}
